package com.tchy.cloud.controller;

import com.tchy.cloud.entity.*;
import org.apache.log4j.Logger;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;

import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.common.service.CommonService;
import org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.tag.vo.datatable.SortDirection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;


/**
 * 工作室
 */
@Controller
@RequestMapping("/studioController")
public class AStudioController {
    private static final Logger logger = Logger.getLogger(AStudioEntity.class.getName());

    @Autowired
    private CommonService commonService;

    /**
     * 工作室审核列表展示页面
     *
     * @return
     */
    @RequestMapping(params = "indexView")
    public ModelAndView indexView() {
        return new ModelAndView("clound/studio/indexView");
    }

//    /**
//     * 工作室审核列表展示页面
//     *
//     * @return
//     */
//    @RequestMapping(params = "indexView2")
//    public ModelAndView indexView2() {
//        return new ModelAndView("clound/studio/indexView2");
//    }


    /**
     * 工作室新增
     *
     * @return
     */
    @RequestMapping(params = "addorupdate")
    public ModelAndView addorupdate(AStudioEntity studioEntity, HttpServletRequest req) {
        String showFields = "";
        if (studioEntity.getStudioId() != null) {
            studioEntity = commonService.getEntity(AStudioEntity.class, studioEntity.getStudioId());
            showFields = this.getObj(studioEntity);
        }
        req.setAttribute("showFields", showFields);
        req.setAttribute("studioEntity", studioEntity);
        return new ModelAndView("clound/studio/addorupdate");
    }


    /**
     * 工作室新增
     *
     * @return
     */


    /**
     * 订单排序确认后页面跳转
     *
     * @return
     */
    @RequestMapping(params = "sortOrder")
    public ModelAndView indexView2(AStudioEntity studioEntity, HttpServletRequest request) {
        String studioId = request.getParameter("id");
        if (null != studioId) {
            studioEntity = commonService.getEntity(AStudioEntity.class, Long.valueOf(studioId));
        }
        request.setAttribute("studioEntity", studioEntity);
        return new ModelAndView("clound/studio/sortOrder");
    }

    /**
     * 工作室查看页面跳转
     *
     * @return
     */
    @RequestMapping(params = "detail")
    public ModelAndView detail(AStudioEntity studioEntity, HttpServletRequest request) {
        String studioId = request.getParameter("id");
        String showFields = "";
        if (null != studioId) {
            studioEntity = commonService.getEntity(AStudioEntity.class, Long.valueOf(studioId));

            showFields = this.getObj(studioEntity);
        }
        request.setAttribute("studioEntity", studioEntity);
        request.setAttribute("showFields", showFields);
        return new ModelAndView("clound/studio/detail");
    }


    /**
     * 工作室列表展示数据
     *
     * @param studioEntity
     * @param request
     * @param response
     * @param dataGrid
     */
    @RequestMapping(params = "datagrid")
    public void datagrid(AStudioEntity studioEntity, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        CriteriaQuery cq = new CriteriaQuery(AStudioEntity.class, dataGrid);
        String createName = request.getParameter("consultantEntity.aCustomerEntity.realname");
        if (StringUtil.isNotEmpty(createName)) {
            cq.createAlias("consultantEntity.aCustomerEntity", "as_customerEntity");
            cq.like("as_customerEntity.realname", '%' + createName + '%');
            studioEntity.getConsultantEntity().getaCustomerEntity().setRealname(null);
        }

        cq.addOrder("sort", SortDirection.asc);
        cq.addOrder("studioId", SortDirection.desc);
        cq.add();
        // 查询条件组装
        HqlGenerateUtil.installHql(cq, studioEntity, request.getParameterMap());
        commonService.getDataGridReturn(cq, true);
        TagUtil.datagrid(response, dataGrid);
    }

//    /**
//     * 工作室管理列表展示数据
//     *
//     * @param studioEntity
//     * @param request
//     * @param response
//     * @param dataGrid
//     */
//    @RequestMapping(params = "datagrid2")
//    public void datagrid2(AStudioEntity studioEntity, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
//        CriteriaQuery cq = new CriteriaQuery(AStudioEntity.class, dataGrid);
//        String createName = request.getParameter("consultantEntity.aCustomerEntity.realname");
//        if (StringUtil.isNotEmpty(createName)) {
//            cq.createAlias("consultantEntity.aCustomerEntity", "as_customerEntity");
//            cq.like("as_customerEntity.realname", '%' + createName + '%');
//            studioEntity.getConsultantEntity().getaCustomerEntity().setRealname(null);
//        }
//        cq.notEq("isReview", 11);
//
//        cq.addOrder("studioId", SortDirection.desc);
//        cq.add();
//        // 查询条件组装
//        HqlGenerateUtil.installHql(cq, studioEntity, request.getParameterMap());
//        commonService.getDataGridReturn(cq, true);
//        TagUtil.datagrid(response, dataGrid);
//    }

    /**
     * 工作室审核页面
     *
     * @param studioEntity
     * @param req
     * @return
     */
    @RequestMapping(params = "review")
    public ModelAndView review(AStudioEntity studioEntity, HttpServletRequest req) {
        String studioId = req.getParameter("id");
        if (null != studioId) {
            studioEntity = commonService.getEntity(AStudioEntity.class, Long.valueOf(studioId));
        }
        req.setAttribute("studioEntity", studioEntity);
        return new ModelAndView("clound/studio/reviewShowView");
    }

    private String getObj(AStudioEntity studioEntity) {
        String obj = studioEntity.getFields();
        String[] object = obj.split(",");
        String inputStr = "";
        for (int i = 0; i < object.length; i++) {
            inputStr += (object[i]);
            if (i != object.length - 1)
                inputStr += ",";
        }
        String sql = "select group_concat(t1.title separator ',') as title from a_columns t1 where t1.columns_id in(" + inputStr + ")";
        Map<String, Object> map = commonService.findOneForJdbc(sql);
        String text = "";
        if (!map.isEmpty())
            text += String.valueOf(map.get("title"));
        return text;
    }


    /**
     * 工作室审核功能
     *
     * @param studioEntity
     * @return
     */
    @RequestMapping(params = "reviewSubmit", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson reviewSubmit(AStudioEntity studioEntity) {
        AjaxJson j = new AjaxJson();
        try {
            if (studioEntity.getStudioId() != null) {//修改
                AStudioEntity entity = commonService.get(AStudioEntity.class, studioEntity.getStudioId());
                MyBeanUtils.copyBeanNotNull2Bean(studioEntity, entity);
                commonService.saveOrUpdate(entity);
            } else {//保存
                commonService.save(studioEntity);
            }
            j.setMsg("操作成功");
        } catch (Exception e) {
            logger.error(e);
            j.setMsg("操作失败");
        }
        return j;
    }


    /**
     * 工作室删除
     *
     * @param studioEntity
     * @return
     */
    @RequestMapping(params = "delStudio", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson delStudio(AStudioEntity studioEntity, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            String studioId = request.getParameter("id");
            if (studioId != null) {//修改
                AStudioEntity entity = commonService.get(AStudioEntity.class, Long.valueOf(studioId));
                commonService.delete(entity);
                j.setMsg("操作成功");
            } else {
                j.setMsg("工作室不存在");
            }
        } catch (Exception e) {
            logger.error(e);
            j.setMsg("操作失败");
        }
        return j;
    }


    /**
     * 排序保存
     *
     * @param studioEntity
     * @return
     */
    @RequestMapping(params = "sortSubmit", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson sortSubmit(AStudioEntity studioEntity, HttpServletRequest req) {
        AjaxJson j = new AjaxJson();
        if (studioEntity.getStudioId() != null) {
            try {
                AStudioEntity entity = commonService.getEntity(AStudioEntity.class, studioEntity.getStudioId());
                MyBeanUtils.copyBeanNotNull2Bean(studioEntity, entity);
                commonService.saveOrUpdate(entity);
                j.setMsg("操作成功");
            } catch (Exception e) {
                logger.error(e);
                j.setMsg("操作失败");
            }
        } else {
            j.setMsg("工作室不存在。");
        }
        return j;

    }

    /**
     * 工作室解禁和封禁
     *
     * @param studioEntity
     * @return
     */
    @RequestMapping(params = "forbidden", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson forbidden(AStudioEntity studioEntity, HttpServletRequest req) {
        AjaxJson j = new AjaxJson();
        String studioId = req.getParameter("id");
        try {
            if (null != studioId) {
                studioEntity = commonService.getEntity(AStudioEntity.class, Long.valueOf(studioId));
                if (studioEntity.getIsAuth() == 0)
                    studioEntity.setIsAuth(1);
                else
                    studioEntity.setIsAuth(0);
            }
            commonService.saveOrUpdate(studioEntity);
            j.setMsg("操作成功");
        } catch (Exception e) {
            logger.error(e);
            j.setMsg("操作失败");
        }
        return j;

    }


    /**
     * 新增及修改的数据处理
     *
     * @param studioEntity
     * @param req
     * @return
     */
    @RequestMapping(params = "saveorupdate", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson saveorupdate(AStudioEntity studioEntity, HttpServletRequest req) {
        AjaxJson j = new AjaxJson();
        Long creator = Long.valueOf(req.getParameter("creator"));//创建人id
        String name = studioEntity.getName();//工作室名称

        String sql = "select * from a_studio where creator=?";
        String sql2 = "select * from a_studio where name=?";
        try {
            ACustomerEntity customer = commonService.getEntity(ACustomerEntity.class, creator);
            AConsultantEntity consultant = commonService.getEntity(AConsultantEntity.class, creator);
            consultant.setaCustomerEntity(customer);
            studioEntity.setConsultantEntity(consultant);
            if (studioEntity.getStudioId() != null) {//更新操作
                AStudioEntity entity = commonService.get(AStudioEntity.class, studioEntity.getStudioId());
                if (!name.equals(entity.getName())) {//名字未改变
                    List<Map<String, Object>> list = commonService.findForJdbc(sql2, new Object[]{name});
                    if (list.size() != 0)
                        j.setMsg("工作室名称已经存在，不允许重复提交。");
                    else {
                        MyBeanUtils.copyBeanNotNull2Bean(studioEntity, entity);
                        commonService.saveOrUpdate(entity);
                    }
                }else{
                    MyBeanUtils.copyBeanNotNull2Bean(studioEntity, entity);
                    commonService.saveOrUpdate(entity);
                }
            } else {//新增操作
                List<Map<String, Object>> list = commonService.findForJdbc(sql2, new Object[]{name});
                if (list.size() != 0)
                    j.setMsg("工作室名称已经存在，不允许重复提交。");
                else {
                    studioEntity.setIsReview(0);//审核
                    studioEntity.setIsAuth(0);//认证
                    studioEntity.setSort(1);//排序
                    studioEntity.setIsRecom(0);
                    commonService.save(studioEntity);
                    j.setMsg("操作成功");
                }
            }

        } catch (Exception e) {
            logger.error(e);
            j.setMsg("操作失败");

        }
        return j;
    }

    /**
     * ts_typeList
     * 认证标签展示
     */
    @RequestMapping(params = "ts_typeList")
    @ResponseBody
    public List ts_typeList(HttpServletRequest req, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();
        String sql = "select typecode,typename from t_s_type where typegroupid = 'ff80808159bcb2df0159bcf038ba0001'";
        List<Map<String, Object>> addressList = commonService.findForJdbc(sql);
        return addressList;
    }


}







